/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.web.filter;

import com.iwindplus.boot.domain.context.HeaderContextHolder;
import com.iwindplus.boot.domain.context.UserContextHolder;
import com.iwindplus.boot.web.manager.context.ContextTransManager;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 请求过滤器.
 *
 * @author zengdegui
 * @since 2020/4/19
 */
@Slf4j
@RequiredArgsConstructor
public class RequestFilter extends OncePerRequestFilter {

    private final ContextTransManager contextTransManager;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain)
        throws ServletException, IOException {

        try {
            contextTransManager.buildRequestHeaderContext(httpServletRequest);
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } finally {
            MDC.clear();
            UserContextHolder.remove();
            HeaderContextHolder.remove();
        }
    }
}